import axios from 'axios'
import Cookie from 'js-cookie'
import {COOKIE_LIST, SERVER_URL} from '@/util/constant'
import store from '@/store/index'
import {router} from '@/router/index'
import {Message} from 'element-ui';

function instance() {
  const get = axios.create({
    timeout: 10 * 1000,
    baseURL: SERVER_URL
  })
  get.interceptors.request.use(function (config) {
    config.headers = {...config.headers, [COOKIE_LIST.AUTHORIZATION]: Cookie.get(COOKIE_LIST.AUTHORIZATION)}
    store.commit('countRequest')
    return config
  }, function (error) {
    return Promise.reject(error)
  })

  get.interceptors.response.use(function (response) {
    store.commit('countResponse')
    return response
  }, function (error) {
    // TODO 暂时跳转login
    console.log('获取请求失败，跳转静态页面')
    store.commit('responseError')
    router.push('/')
    Message({
      message: '请重新登录',
      type: 'error',
      showClose: true
    })
    return Promise.reject(error)
  })
  return get
}

export const get = instance()
